package com.xxg.renrenorder.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.xxg.renrenorder.dao.bean.CommissionSettingInfo;
import com.xxg.renrenorder.dao.bean.OrderMasterInfo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * 手续费配置信息
 *
 * @author szj
 * @date 2022/1/4
 */
@Repository
public class CommissionSettingInfoDao {
    private final MongoTemplate mongoTemplate;

    public CommissionSettingInfoDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "commissionSettingInfo";
        MongoCollection<org.bson.Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(CommissionSettingInfo.class);
            createIndex(collection);
        }
    }

    /**
     * 创建索引
     *
     * @param collection 数据集
     */
    private void createIndex(MongoCollection<Document> collection) {
        IndexOptions indexOptions = new IndexOptions().unique(true);
        collection.createIndex(Indexes.descending("groupId"), indexOptions);
    }

    public List<CommissionSettingInfo> findAll() {
        return mongoTemplate.findAll(CommissionSettingInfo.class);
    }

    public void save(CommissionSettingInfo commissionSettingInfo) {
        mongoTemplate.save(commissionSettingInfo);
    }

    public CommissionSettingInfo findByGroupId(Integer groupId) {
        Query query = new Query(where("groupId").is(groupId));
        return mongoTemplate.findOne(query, CommissionSettingInfo.class);
    }
}
